package com.binguo.api.service;


import com.alibaba.fastjson.JSONObject;
import com.binguo.api.alipay.util.PriceUtil;
import com.binguo.api.form.YizhifuQueryRechargeForm;
import com.binguo.api.form.YizhifuRechargeForm;
import com.binguo.api.schedule.DataLoadService;
import com.binguo.common.exception.ServiceException;
import com.binguo.helper.FaceHelperV3;
import com.binguo.helper.TXTHelper;
import com.binguo.model.api.vo.YizhifuBinguoOrderVO;
import com.binguo.model.mapper.BinguoOrderMapper;
import com.binguo.model.model.*;
import com.binguo.model.repository.*;
import com.binguo.service.ShopService;
import com.binguo.thirdPay.FtpUtils;
import com.binguo.thirdPay.MD5Util;
//import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//import org.apache.poi.ss.usermodel.Cell;
//import org.apache.poi.ss.usermodel.Row;
//import org.apache.poi.ss.usermodel.Sheet;
//import org.apache.poi.ss.usermodel.Workbook;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author yuritian
 * @Title: YizhifuService
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2019-07-1008:50
 */
@Service
public class YizhifuService {

    private final Integer SHOPID = 74;

    private final String FAILPATH = "/opt/yixingdianxin/";

//    private final String FAILPATH = "/Users/yuritian/Documents/云澎对接文档";

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");



    @Autowired
    CustomerRepository customerRepository;

    @Autowired
    PayCardRepository payCardRepository;

    @Autowired
    BinguoOrderRepository binguoOrderRepository;

    @Resource
    BinguoOrderMapper binguoOrderMapper;

    @Autowired
    FaceHelperV3 faceHelperV3;

    @Autowired
    FaceRepository faceRepository;

    @Autowired
    CustomerExtendRepository customerExtendRepository;

    @Autowired
    ShopService shopService;


    public static void main(String[] args) {
        YizhifuService yizhifuService = new YizhifuService();
        System.out.println(yizhifuService.queryBalance("15306159110","陈志光"));
    }


    public boolean checkSign(String valuelist, String sign) {
        System.out.println(valuelist);
        String trueSign = null;
        trueSign = MD5Util.getMD5UpperString(valuelist);
        System.out.println(trueSign);
        if (sign.equals(trueSign)) {
            return true;
        }
        return false;
    }

    public JSONObject getCustomer(String phoneNum,String name) {
        JSONObject result = new JSONObject();
        Condition condition = new Condition(Customer.class);
        condition.or().andEqualTo("phone", phoneNum)
                .andEqualTo("name", name);
        List<Customer> customerList = customerRepository.findByCondition(condition);
        if (customerList != null && customerList.size() > 0) {
            result.put("ResultCode","0000");
            result.put("ResultMsg","成功");
            return result;
        }else {
            result.put("ResultCode","0200");
            result.put("ResultMsg","账户不存在");
            return result;
        }
    }

    public JSONObject rechargeCustomer(YizhifuRechargeForm form) {
        JSONObject result = new JSONObject();
        Long amount = Long.parseLong(form.getAmount());
        Condition condition = new Condition(Customer.class);
        condition.or().andEqualTo("phone", form.getPhone())
                .andEqualTo("name",form.getName());
        List<Customer> customerList = customerRepository.findByCondition(condition);
        if (customerList != null && customerList.size() > 0) {
            Customer customer = customerList.get(0);
            Condition payCardCondition = new Condition(PayCard.class);
            payCardCondition.or().andEqualTo("customerid", customer.getId())
                    .andEqualTo("shopid", SHOPID);
            PayCard payCard = payCardRepository.findByCondition(payCardCondition).get(0);
            payCard.setAccountbalance(payCard.getAccountbalance() + amount);
            BinguoOrder binguoOrder = new BinguoOrder();
            binguoOrder.setShopid(SHOPID);
            binguoOrder.setSerialnumber(form.getOrderSeq());
            binguoOrder.setOrderno("YXDH"+form.getOrderNum());
            binguoOrder.setTransactionid("YunPeng" + System.currentTimeMillis());
            binguoOrder.setCardid(Integer.parseInt(payCard.getCardno()));
            binguoOrder.setCardno(payCard.getCardno());
            binguoOrder.setCustomerid(customer.getId());
            binguoOrder.setCustomername(customer.getName());
            binguoOrder.setCustomerphone(customer.getPhone());
            binguoOrder.setOrdertype(3);
            binguoOrder.setSource(Byte.parseByte("3"));
            binguoOrder.setTotalquantity(1);
            binguoOrder.setTotalfee(amount);
            binguoOrder.setRealfee(amount);
            binguoOrder.setPaystatus(Byte.parseByte("1"));
            try {
                binguoOrder.setPaytime(DATE_FORMAT.parse(form.getOrderDate()));
            } catch (ParseException e) {
                result.put("ResultCode","9999");
                result.put("ResultMsg","未知错误");
                return result;
            }
            binguoOrder.setCreated(new Date());
            binguoOrderRepository.save(binguoOrder);
            payCardRepository.update(payCard);
            result.put("ResultCode","0000");
            result.put("ResultMsg","成功");
            return result;
        } else {
            result.put("ResultCode","0200");
            result.put("ResultMsg","账户不存在");
            return result;
        }
    }

    public JSONObject queryBalance(String phonenum ,String name) {
        JSONObject result = new JSONObject();
        Condition condition = new Condition(Customer.class);
        condition.or().andEqualTo("phone", phonenum)
                .andEqualTo("name",name);
        List<Customer> customerList = customerRepository.findByCondition(condition);
        if (customerList != null && customerList.size() > 0) {
            Customer customer = customerList.get(0);
            Condition payCardCondition = new Condition(PayCard.class);
            payCardCondition.or().andEqualTo("customerid", customer.getId())
                    .andEqualTo("shopid", SHOPID);
            PayCard payCard = payCardRepository.findByCondition(payCardCondition).get(0);
            result.put("ResultCode","0000");
            result.put("ResultMsg","成功");
            result.put("Amount", PriceUtil.changeF2Y(payCard.getAccountbalance()));
            return result;
        } else {
            result.put("ResultCode","0200");
            result.put("ResultMsg","账户不存在");
            result.put("Amount","0");
            return result;
        }
    }

    public JSONObject queryRecharge(YizhifuQueryRechargeForm form) {
        JSONObject result = new JSONObject();
        Long amount = Long.parseLong(form.getAmount());
        Condition condition = new Condition(Customer.class);
        condition.or().andEqualTo("phone", form.getPhone())
                    .andEqualTo("name",form.getName());
        List<Customer> customerList = customerRepository.findByCondition(condition);
        if (customerList != null && customerList.size() > 0) {
            Condition bingguoOrderCondition = new Condition(BinguoOrder.class);
            bingguoOrderCondition.or().andEqualTo("orderno", "YXDH"+form.getOrderNum())
                    .andEqualTo("serialnumber", form.getOrderSeq());
            List<BinguoOrder> binguoOrderList = binguoOrderRepository.findByCondition(bingguoOrderCondition);
            if (null == binguoOrderList || binguoOrderList.size() == 0) {
                result.put("ResultCode","0004");
                result.put("ResultMsg","订单不存在");
                return result;
            }
            BinguoOrder binguoOrder = binguoOrderList.get(0);
            result.put("ResultCode","0000");
            result.put("ResultMsg","成功");
            return result;
        } else {
            result.put("ResultCode","0200");
            result.put("ResultMsg","账户不存在");
            return result;
        }
    }

    public void createDayTXT(String sqldate) throws IOException{
        SimpleDateFormat txtFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sqldate.replaceAll("-","");
        String shopCode = DataLoadService.shopYiZhiFuMap.get(SHOPID).getShopCode();
        String filePath = TXTHelper.creatTxtFile(FAILPATH, date + shopCode);


        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            // 文件路径
            File file = new File(filePath);
            // 将文件读入输入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();
            YizhifuBinguoOrderVO yizhifuBinguoOrderVO = binguoOrderMapper.findYizhifuOrder(sqldate+" 00:00:00",sqldate+" 23:59:59");
            String head = shopCode + "|"+ date + "|" + yizhifuBinguoOrderVO.getCount() + "|" + yizhifuBinguoOrderVO.getSum() + "\r\n";
            buf.append(head);
            Condition condition = new Condition(BinguoOrder.class);
            condition.or().andEqualTo("shopid",SHOPID)
                    .andEqualTo("ordertype",3)
                    .andBetween("created",sqldate+" 00:00:00",sqldate+" 23:59:59");
            List<BinguoOrder> binguoOrderList = binguoOrderRepository.findByCondition(condition);
            for (BinguoOrder binguoOrder : binguoOrderList){
                Customer customer = customerRepository.findById(binguoOrder.getCustomerid());
                String body = binguoOrder.getOrderno().substring(4) + "|" + binguoOrder.getSerialnumber() + "|" + binguoOrder.getTotalfee() + "|"+ customer.getPhone() + "|" + txtFormat.format(binguoOrder.getCreated()) + "|" + "\r\n";
                buf.append(body);
            }
            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buf.toString().toCharArray());
            pw.flush();
            FtpUtils ftpUtils = new FtpUtils();
            ftpUtils.uploadFile("/"+shopCode,date + shopCode+".txt",new ByteArrayInputStream(buf.toString().getBytes()));
        } catch (IOException e1) {
            // TODO 自动生成 catch 块
            throw new ServiceException(e1.getMessage());
//            throw new ServiceException(YZF_TXT_ERROR);
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }
/*
    public void uploadImg(){
        String filePath = "/Users/yuritian/Documents/YunpengWork/binguoDevelop/api/src/main/resources/img/images/20190710.xlsx";
        Workbook workbook = null;
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        Integer cellNum;
        try {
            is = new FileInputStream(filePath);
            if(".xls".equals(extString)){
                workbook = new HSSFWorkbook(is);
            }else if(".xlsx".equals(extString)){
                workbook = new XSSFWorkbook(is);
            }
            Sheet sheet = workbook.getSheetAt(0);
            int total = sheet.getLastRowNum();
            for (int rowNum = 373;rowNum<=total;rowNum++){
                Customer customer = new Customer();
                Row row = sheet.getRow(rowNum);
                cellNum = 1;
                Cell cell = row.getCell(cellNum++);
                customer.setShopCustomerid(cell.getStringCellValue());
                System.out.println(cell.getStringCellValue());
                cell = row.getCell(cellNum++);
                customer.setName(cell.getStringCellValue());
                System.out.println(cell.getStringCellValue());
                cell = row.getCell(cellNum++);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                customer.setPhone(cell.getStringCellValue());
                System.out.println(cell.getStringCellValue());
                String uploadResultURL = null;
                String uuid = UUID.randomUUID().toString();
                File file = new File("/Users/yuritian/Documents/YunpengWork/binguoDevelop/api/src/main/resources/img/images/"+customer.getShopCustomerid().substring(1)+customer.getName()+".jpg");
                System.out.println("/Users/yuritian/Documents/YunpengWork/binguoDevelop/api/src/main/resources/img/images/"+customer.getShopCustomerid().substring(1)+customer.getName()+".jpg");
                JSONObject uploadResult = null;
                try {
                     uploadResult = JSONObject.parseObject(uploadIMGHelper.upload(file,uuid+".png"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                uploadResultURL = "http://img.binguoai.com/" + uploadResult.getString("key");
                System.out.println(uploadResultURL);
                if (FaceHelperV3.detectFace(uploadResultURL) > 65) {
                    customerRepository.save(customer);
                    String faceId = FaceHelperV3.createPerson("74", "74_" + customer.getId(), uploadResultURL);
                    if (faceId == null) {
                        System.out.println(customer.getShopCustomerid()+customer.getName()+" 人脸创建失败");
                        customerRepository.deleteById(customer.getId());
                        continue;
                    }
                    Face face = new Face();
                    face.setFaceid(faceId);
                    face.setFaceurl(uploadResultURL);
                    face.setPersionid("74_" + customer.getId());
                    face.setCustomerId(customer.getId());
                    faceRepository.save(face);
                    CustomerExtend customerExtend = new CustomerExtend();
                    customerExtend.setGroupName("宜兴电信");
                    customerExtend.setGroupId(57);
                    customerExtend.setCustomerId(customer.getId());
                    customerExtend.setUserStatus(1);
                    customerExtend.setShopId(74);
                    customerExtend.setIsAudit(1);
                    customerExtendRepository.save(customerExtend);
                    String name = shopService.findShopNameById(74) + "卡";
                    PayCard payCard = new PayCard();
                    payCard.setShopid(74);
                    payCard.setCustomerid(customer.getId());
                    payCard.setCardtype(CardType.BINGUO_CARD.getCode().byteValue());
                    payCard.setName(name);
                    payCardRepository.save(payCard);
                    payCard.setCardno(payCard.getId().toString());
                    payCardRepository.update(payCard);
                }else {
                    System.out.println(customer.getShopCustomerid()+customer.getName()+ "人脸图片分数不够");
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //FaceHelperV3.detectFace("http://img.binguoai.com/cb230edd-144f-44a7-aec1-d822b630d5e1.png");

    }*/

}
